/* menu card view as a nested list component*/

RefApp.views.MenuCard = Ext.extend(Ext.NestedList, {
    fullscreen : true,
    displayField : 'text',
    emptyText : 'brak', 
    items: [{
  		xtype: 'menuPopup'
  	}],
  	
    getDetailCard: function(item, parent) 
    {
    	/* this function describes each leaf items appearance*/
    	
    	var itemData = item.attributes.record.data,
        possibilities = [];
    	
    	//merge ingredients list into string (splited by ", ")
        var ingredientsTxt = itemData.ingredients.join(', ');
        
        for (var i = 0; i < itemData.possibilities.length; i++ )
    	{
        	/* for each size describes order button */
    		possibilities[i] = 
    		{
    				text : itemData.possibilities[i] + ((isInt(itemData.possibilities[i])) ? ' cm' : ''),
    				xtype: 'button',
    				ui: 'action',
    				handler: function() {
    					/* on-click event */
    					var carttab = RefApp.views.cartCard.tab,
    						size = this.text,
                            badgenumber = parseInt(carttab.badgeText, 10),
                            nextnumber = isNaN(badgenumber) ? 1 : badgenumber+1; // increase cart badge number
    					
    						// show popup panel
    						Ext.dispatch({
    							controller : 'Menu',
    							action : 'showPopup',
    							size : size,
    							itemData : itemData,
    						});
    				}
    		};
        }
        
    	var detailCard = new Ext.Panel({
    		/* define leaf view */
    		scroll: 'vertical',
    		styleHtmlContent: true,
  			items: [{
  					html: '<h2>' + itemData.text + '</h2>'
  				},
  				{
  					html: '<img src="res/images/'+((itemData.picture) ? itemData.picture : 'default')+'.png" /></br>' ,
  					width: 150,
  					height: 150
  				},
  				{
  					html: '</br><b>Opis:</b></br>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis posuere consectetur mi. Mauris eu scelerisque risus. Aenean euismod sodales nibh. Nunc in nulla ac dui porttitor adipiscing a eu tortor. Nulla porta faucibus lorem, at sollicitudin ante ultrices a. Donec a nulla tellus.</br>'
  				},
  				{
  					html: '</br><b>Składniki:</b></br>'+ingredientsTxt+'</br></br><b>Rozmiar:</b></br>'
  				},
  			    {
  					/* added described buttons to leaf panel */
  					width: 200,
  			       	layout: 
  			       	{
  			       		type: 'hbox'       		
  			       	},
  			       	defaults:
  			       	{
  			       		flex: 1
  			       	},
  			       	items: [possibilities]
  				}
  			]
        });
                        
        detailCard.update(itemData);
                
        // back button - parent record is undefined if leaf on the first depth on nested list is tapped
        this.backButton.setText(!parent.attributes.record ? this.title : parent.attributes.record.data.text);
        
        //PROBLEM - set itemData.text as title on nestedlist toolbar
        this.title = itemData.text;
        
        detailCard.doLayout();
        return detailCard;
    },
    
    //redefined onBackTap function (only for change title of nested list in the leaf card)- i think it's better to delete this
    onBackTap: function() {
        var currList      = this.getActiveItem(),
            currIdx       = this.items.indexOf(currList);
        
        //the only line added by me:
        if (this.onlyPromotions)
        	this.title = "Promocje";
        else
        	this.title = "Menu";
        
        if (currIdx != 0) {
            var prevDepth     = currIdx - 1,
                prevList      = this.items.getAt(prevDepth),
                recordNode    = prevList.recordNode,
                record        = recordNode.getRecord(),
                parentNode    = recordNode ? recordNode.parentNode : null,
                backBtn       = this.backButton,
                backToggleMth = (prevDepth !== 0) ? 'show' : 'hide',
                backBtnText;

            this.on('cardswitch', function(newCard, oldCard) {
                var selModel = prevList.getSelectionModel();
                this.remove(currList);
                if (this.clearSelectionDelay) {
                    Ext.defer(selModel.deselectAll, this.clearSelectionDelay, selModel);
                }
            }, this, {single: true});
            
            this.setActiveItem(prevList, {
                type: this.cardSwitchAnimation,
                reverse: true,
                scope: this
            });
            this.syncToolbar(prevList);
            
            // cut address
            Ext.dispatch({
				controller : 'Menu',
				action : 'addressCut',
			});
        }
    },
   // template describing style of the item on the nested list
   getItemTextTpl: function()
   {
	   /* item's appearance on list */
    	var template = 
    			'{text}'+
                '<tpl if="leaf == true">'+
                        '<div class="metadata">'+
                                '<tpl for="ingredients">'+
                                        '{.}'+
                                        '{[xindex < xcount ? ", " : ""]}'+
                                '</tpl>'+
                        '</div>'+
                        '<div class="right">{price} ' + RefApp.Config.currency + '</div>'+
                '</tpl>';
    	
    	return template;
   },
   listeners: {
	   // itemtap event listener - set proper url
	   itemtap: function(list, index, item, e){
	  		var hist = Ext.History;					// history reference
	  		
	  		var adr = hist.getToken().split('/'),	// split addres
	  			des = this.items.indexOf(list) + 1;	// actual depth

	  		while(adr.length > des)
	  			adr.pop();							// pop address - prevent url modifications and some device backButton actions, which make url wrong

	  		adr.push(index);						// push act id to the end of url
	  		adr = adr.join('/');					// join everything
	  		hist.add(adr);							// set address
		}
   }, 
   
   // function to go to the zero depth in nestedList, keeping "healthy" all backButtons and so on.
   setRootActive: function(){
       var list = this;
       var firstList = list.items.getAt(0);
       // remove all list from zero to max depth
       for(i=(list.items.length-1);i >= 1;i--){
           list.remove(list.items.getAt(i));
       }
       // go to first list
       list.setActiveItem(firstList, {
               type: 'slide',
               reverse: true,
               scope: this
       });
       list.syncToolbar(firstList);		// synchronize toolbar
       list.onBackTap();				// synchronize back button
   }

    	  
});

Ext.reg('menuCard', RefApp.views.MenuCard);

function isInt(x) { 
	var y = parseInt(x); 
	if (isNaN(y)) 
		return false; 
	return x == y && x.toString() == y.toString(); 
} 